package com.example.framework509.common.typeHandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StringArrayTypeHandler extends BaseTypeHandler<Object[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object[] parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, serializeObject(parameter));
    }

    @Override
    public Object[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return (Object[]) stringSerializeObject(columnName);
    }

    @Override
    public Object[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return (Object[]) stringSerializeObject(rs.getString(columnIndex));
    }

    @Override
    public Object[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return (Object[]) stringSerializeObject(cs.getNString(columnIndex));
    }

    //序列化为字符串
    private String serializeObject(Object object) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
            out.writeObject(object);
            //必须是ISO-8859-1
            String objectStr = byteArrayOutputStream.toString("ISO-8859-1");
            out.close();
            byteArrayOutputStream.close();
            return objectStr;
        } catch (Exception e) {
            return "序列化异常";
        }
    }

    //反序列化为对象
    public Object stringSerializeObject(String objectStr) {
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(objectStr.getBytes(StandardCharsets.ISO_8859_1));
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Object object = objectInputStream.readObject();
            objectInputStream.close();
            byteArrayInputStream.close();
            return object;
        } catch (Exception e) {
            return null;
        }
    }

}

